package cn.wzg.datastorage;

import static java.net.HttpURLConnection.HTTP_OK;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.json.JSONObject;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.HttpsURLConnection;
import cn.wzg.datastorage.utils.StreamUtil;

public class LoginActivity extends AppCompatActivity {
    private EditText et_name, et_pwd;
    private final String link = "https://www.wanandroid.com/user/login";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        et_name = findViewById(R.id.et_name);
        et_pwd = findViewById(R.id.et_pwd);
        //2.读取保存的用户名和密码，若不为空则设置到编辑框内
        SharedPreferences sp  = getSharedPreferences("aaa", MODE_PRIVATE);
        String name = sp.getString("name", "");
        String pwd = sp.getString("pwd", "");
        if(!name.isEmpty()){
            et_name.setText(name);
            et_pwd.setText(pwd);
        }
    }
    public void login(View view) {
        String name = et_name.getText().toString();
        String pwd = et_pwd.getText().toString();
        String param = "username=" + URLEncoder.encode(name) +
                "&password=" + URLEncoder.encode(pwd);
        new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(link);//创建URL对象
                    //获取HttpsURLConnection对象
                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");//设置请求方式
                    conn.setConnectTimeout(5000);//设置超时时间（毫秒）
                    conn.setDoOutput(true);//设置为true，可以打开输出流
                    OutputStream outputStream = conn.getOutputStream();//得到输出流
                    outputStream.write(param.getBytes(StandardCharsets.UTF_8));//写数据
                    outputStream.flush();//清空缓冲区
                    outputStream.close();//关闭输出流
                    //判断网络访问是否成功
                    if (conn.getResponseCode() == HTTP_OK) {
                        //获取输入流
                        InputStream stream = conn.getInputStream();
                        //从流中获取字符串
                        String json = StreamUtil.stream2String(stream);
                        JSONObject object=new JSONObject(json);
                        int errorCode = object.optInt("errorCode");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(errorCode==0){
                                    Toast.makeText(LoginActivity.this, "登录成功！", Toast.LENGTH_SHORT).show();
                                    //1.保存用户名和密码
                                    SharedPreferences sp  = getSharedPreferences("aaa", MODE_PRIVATE);
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString("name",name);
                                    edit.putString("pwd",pwd);
                                    edit.apply();
                                }else{
                                    String string = object.optString("errorMsg");
                                    Toast.makeText(LoginActivity.this, string, Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                    conn.disconnect();//关闭连接
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }.start();
    }
}